package com.lu.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.lu.common.utils.MD5Utils;
import com.lu.common.utils.R;
import com.lu.common.utils.TokenUtils;
import com.lu.system.management.domain.MenuDO;
import com.lu.system.management.domain.Tree;
import com.lu.system.management.domain.UserDO;
import com.lu.system.management.service.MenuService;
import com.lu.system.management.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/mail/systemLogin/")
public class LoginController {

    @Autowired
    UserService userService;
    @Autowired
    MenuService menuService;

    @PostMapping(value = "/toLoginMsg")
    public R toLoginMsg(){
        R r=new R();
        r.put("code",1001);
        r.put("msg","token失效请求重新登陆");
        return r;
    }

    @PostMapping(value = "/login")
    public R login(String username, String password) throws Exception {
        R r=new R();


        Map<String, Object> map = new HashMap<>(16);
        map.put("username", username);
        // 查询用户信息
        UserDO user = userService.list(map).get(0);

        //根据获取用户信息
        String tokenJwt
                = TokenUtils.createJWT(JSONObject.toJSONString(user));

        // 账号不存在
        if (user == null) {
            r.put("code",-1);
            r.put("msg","账号或密码不正确");
            return r;
        }

        // 密码错误
        if (!MD5Utils.encrypt(username,password).equals(user.getPassword())) {
            r.put("code",-2);
            r.put("msg","账号或密码不正确");
            return r;
        }

        map.clear();
        map.put("access_token",tokenJwt);
        r.put("code",0);
        r.put("data",map);
        r.put("msg","登入成功");
        return r;
    }

    @GetMapping("/menu")
    public R indexMenu(HttpServletRequest request) throws Exception{
        UserDO userDO = TokenUtils.parseJwtForUserInfo(request);
        List<Tree<MenuDO>> menus = menuService.listMenuTree(userDO.getUserId());
        Map<String, Object> map = new HashMap();
        map.put("data",menus);
        return R.ok(map);
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping(value = "/getUserInfo")
    public R getUserInfo(HttpServletRequest request) throws Exception {
        R r=new R();
        UserDO userDO =TokenUtils.parseJwtForUserInfo(request);
        r.put("code",0);
        r.put("msg","获取用户信息成功");
        r.put("data",userDO);
        return  r;
    }

}
